<template>
  <div class="myInfoPage">
      <h1>개인정보관리</h1>
      <el-form class="updateFrm loginFrm" v-loading="frmLoading" :model="updateFrm" :rules="rules" ref="updateFrm" label-position="top" label-width="100px">
          <el-form-item label="아이디(이메일)" prop="email">
              <el-input v-model="updateFrm.email" placeholder="example@workwiz.com" disabled></el-input>
          </el-form-item>
          <el-form-item v-if="updateFrm.login_type==0" label="비밀번호" prop="password">
              <el-input type="password" v-model="updateFrm.password" placeholder="영문, 숫자, 특수문자 포함 8자 이상 입력" autocomplete="off" @blur="resizePwd"></el-input>
          </el-form-item>
          <el-form-item v-if="updateFrm.login_type==0" label="비밀번호확인" prop="password_confirmation">
              <el-input type="password" v-model="updateFrm.password_confirmation" placeholder="비밀번호를 한번 더 입력해주세요." autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="휴대폰번호" prop="phone">
            <div class="authBar" @click="setAuth">
              <el-col :span="17">
                <el-input disabled placeholder="본인인증 버튼을 선택해주세요." v-model="updateFrm.phone" autocomplete="off"></el-input>
              </el-col>
              <el-col :span="7">
                <el-button class="minBtn" :loading="authLoading" plain>{{isAuth&&!isFirst?'인증완료':'변경'}}</el-button>
              </el-col>
            </div>
            <div class="el-form-item__success" v-if="success.auth">{{success.auth}}</div>
          </el-form-item>
          <el-form-item label="이름" prop="name" class="regName">
            <el-col :span="14">
              <el-input disabled v-model="updateFrm.name" placeholder="이름을 입력해주세요."></el-input>
            </el-col>
            <el-col :span="10">
              <el-radio-group disabled v-model="updateFrm.sex">
                  <el-radio-button label="1">남자</el-radio-button>
                  <el-radio-button label="2">여자</el-radio-button>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item label="생년월일" prop="birthday">
              <el-date-picker disabled value-format="yyyy-MM-dd" placeholder="YYYY-MM-DD" v-model="updateFrm.birthday" style="width: 100%;" prefix-icon="none"></el-date-picker>
          </el-form-item>
          <el-form-item class="minMrb" label="주소" prop="zip_code">
              <el-col :span="17">
                <el-input readonly v-model="updateFrm.zip_code" placeholder="우편번호를 검색해주세요."></el-input>    
              </el-col>
              <el-col :span="7">
                <el-button class="minBtn" :loading="searchAdsLoading" @click="searchAds" plain>검색하기</el-button>
              </el-col>
          </el-form-item>
          <el-form-item class="minMrb" prop="city_area">
              <el-input readonly v-model="updateFrm.city_area" placeholder="주소"></el-input>
          </el-form-item>
          <el-form-item prop="address">
              <el-input v-model="updateFrm.address" ref="address" placeholder="상세주소"></el-input>
          </el-form-item>
          <el-form-item label="가입경로" prop="registration_path">
              <el-select disabled style="width:100%" v-model="updateFrm.registration_path" placeholder="선택">
                  <el-option v-if="pathArry.length" v-for="(item,index) in pathArry" :label="item.value" :value="item.id" :key="index"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item class="regAgr" label="이용약관동의">
              <el-checkbox v-model="checkAll" @change="handleCheckAllChange">전체 약관 동의</el-checkbox>
              <div class="rules">
                <template v-if="serviceArry">
                  <el-checkbox-group v-model="checkedAgrValue" @change="handleCheckedAgrChange">
                    <div class="item" v-for="(item,index) in serviceArry" :key="'ser_'+index">
                      <el-checkbox disabled :label="item.id">{{item.title}}<el-link @click.prevent="showTos(item.id)">자세히보기</el-link></el-checkbox>
                    </div>
                  </el-checkbox-group>
                </template>
                <div class="item times">
                  <div class="txt">개인정보유효기간</div>
                  <el-radio-group disabled v-model="updateFrm.expire_years_personal">
                      <el-radio :label="1">1년</el-radio>
                      <el-radio :label="5">5년</el-radio>
                      <el-radio :label="30">10년</el-radio>
                      <el-radio :label="0">탈퇴시</el-radio>
                  </el-radio-group>
                </div>
                <div class="item">
                  <el-checkbox :true-label="1" :false-label="0" v-model="updateFrm.AD_notice" @change="handleCheckedAgrChange">  마케팅정보 수신동의 (선택)  </el-checkbox>
                </div>
                <div class="item">
                  <el-checkbox :true-label="1" :false-label="0" v-model="updateFrm.offer_notice" @change="handleCheckedAgrChange"> 취업/채용 등 알림동의 (선택) </el-checkbox>
                </div>
                <div class="item" v-if="thirdServices">
                  <el-checkbox :true-label="1" :false-label="0" v-model="updateFrm.third_party_services" @change="handleCheckedAgrChange">{{thirdServices.title}} (선택) <el-link @click.prevent="showTos(thirdServices.id)">자세히보기</el-link></el-checkbox>
                </div>
              </div>
          </el-form-item>
          <el-form-item>
              <center>
                <el-button :loading="loading" type="primary" class="subBtn" @click="submitForm">수정하기</el-button>
                <el-button class="subBtn offBtn" @click="cancelAccount">탈퇴하기</el-button>
              </center>
          </el-form-item>
          <el-dialog class="dialogRule" :visible.sync="isShowDialog">
              <div slot="title"><h3>{{dialogTit}}</h3></div>
              <div class="dialogCon" v-loading="isConLoading">
                  <div class="con" v-html="dialogCon||'내용 없음'"></div>
              </div>
              <span slot="footer" class="dialog-footer">
                  <el-button type="primary" style="width:100%" @click="isShowDialog = false">확인</el-button>
              </span>
          </el-dialog>
      </el-form>
      <el-dialog
        class="dialogDaum"
        title=""
        :visible.sync="dialogVisible"
        @close="closeBox"
        >
        <div ref="daumBox"></div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="closeBox">확인</el-button>
        </span>
      </el-dialog>      
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import {
  getUserInfo,
  personalUpdate,
  sendVerCode,
  registrationPathOption,
  checkVerificationCode,
  areaList,
  privacyPolicy,
  thirdPartyServiceAgreement,
  getPolicy,
  getService,
  showTos,
  certification,
  destroy
} from '@/api';
import { parseTime, Local, removeNull } from '@/utils'

export default {
  name: '',
  components: {},
  props: [],
  data () {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback();
      } else if (!value.match(/(?=.*\d)(?=.*[a-z]).{8,}/)) {
        callback(new Error('새비밀번호 형식이 틀렸습니다.'));
      } else {
        if (this.updateFrm.password_confirmation !== '') {
          this.$refs.updateFrm.validateField('password_confirmation');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (this.updateFrm.password) {
        if (value === '') {
          callback(new Error('새 비밀번호 확인을 입력하지 않았습니다.'));
        } else if (value !== this.updateFrm.password) {
          callback(new Error('비밀번호와 비밀번호 확인이 다릅니다.'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      isFirst: true,
      frmLoading: true,
      loading: false,
      searchAdsLoading: false,
      sendTime: '',
      timer: null,
      checkAll: false,
      checkedAgrValue: [],
      thirdServices: null,
      dialogTit: '',
      dialogCon: '',
      isShowDialog: false,
      isConLoading: false,
      isAuth: false,
      authLoading: false,
      errors: {
        email: '',
        zip_code: ''
      },
      success: {
        email: '',
        auth: '',
      },
      pathArry: [],
      oldPhone: '',
      updateFrm: {
        email: '',
        password: '',
        password_confirmation: '',
        name: '',
        login_type: 0,
        sex: 1,
        birthday: '',
        phone: '',
        zip_code: '',
        city_area: '',
        address: '',
        registration_path: '',
        expire_years_personal: '',
        expire_privacy_created: '',
        AD_notice: 0,
        offer_notice: 0,
        third_party_services: 0,
      },
      rules: {
        password: [
          { required: false, validator: validatePass, trigger: 'blur' }
        ],
        password_confirmation: [
          { required: false, validator: validatePass2, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '본인인증을 진행해 주세요.', trigger: 'change' }
        ],
        name: [
          { required: true, message: '본인인증을 진행해 주세요.', trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '본인인증을 진행해 주세요.', trigger: 'change' }
        ],
        zip_code: [
          { required: true, message: '우편번호를 검색해주세요.', trigger: 'blur' }
        ],
        city_area: [
          { required: true, message: '주소를 입력해 주세요.', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '상세 주소를 입력해 주세요.', trigger: 'blur' }
        ],
        registration_path: [
          { required: true, message: '등록경로를선택하십시오', trigger: 'change' }
        ]
      },
      serviceArry: null,
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  created () {
    let timestamp = (new Date()).valueOf(), _endTime = Local.get('safeTime');
    if ((!_endTime || _endTime && timestamp > _endTime) && this.userInfo.login_type == 0) {
      Local.remove('safeTime')
      this.$router.replace('/my/check')
    }
    // this.updateFrm.expire_privacy_created=parseTime(new Date(),'{y}-{m}-{d}');
    this.getUserInfo();
    this.getPathData();
    this.getService();
    this.thirdPartyServiceAgreement()
  },
  mounted () { },
  methods: {
    async getUserInfo () {
      let res = await getUserInfo();
      if (res.code == 200) {
        this.frmLoading = false
        this.updateFrm.email = res.data.email
        this.updateFrm.sex = res.data.sex
        this.updateFrm.login_type = res.data.login_type
        this.updateFrm.name = res.data.name
        this.updateFrm.birthday = res.data.birthday
        this.updateFrm.phone = res.data.phone
        this.updateFrm.zip_code = res.data.zip_code
        this.updateFrm.city_area = res.data.city_area
        this.updateFrm.address = res.data.address
        this.updateFrm.registration_path = res.data.registration_path
        this.updateFrm.expire_years_personal = res.data.expire_years_personal
        this.updateFrm.AD_notice = res.data.AD_notice
        this.updateFrm.offer_notice = res.data.offer_notice
        this.updateFrm.third_party_services = res.data.third_party_services

        res.data.AD_notice && this.checkedAgrValue.push(3);
        res.data.offer_notice && this.checkedAgrValue.push(4);
        res.data.third_party_services && this.checkedAgrValue.push(5);
        res.data.AD_notice && res.data.offer_notice && res.data.third_party_services && (this.checkAll = true)

        this.oldPhone = res.data.phone;
        this.isAuth = true;
      } else {
        this.frmLoading = false
      }
    },
    async thirdPartyServiceAgreement () {
      let res = await thirdPartyServiceAgreement({ type: 0 });
      if (res.code == 200) {
        this.thirdServices = res.data[0]
      }
    },
    async getPathData () {
      let res = await registrationPathOption();
      if (res.code == 200) {
        this.pathArry = res.data;
      }
    },
    async getService () {
      let res = await getService({ type: 0 });
      if (res.code == 200) {
        this.getPolicy(res.data);
      }
    },
    async getPolicy (serviceArry) {
      let res = await getPolicy({ type: 0 });
      if (res.code == 200) {
        this.serviceArry = serviceArry.concat(res.data)
        let _arry = [];
        this.serviceArry.forEach(item => {
          _arry.push(item.id)
        });
        this.checkedAgrValue = _arry;
      }
    },
    async showTos (id) {
      this.isShowDialog = true;
      this.isConLoading = true;
      let res = await showTos({ id: id });
      if (res.code == 200) {
        this.dialogTit = res.data.title;
        this.dialogCon = res.data.content;
        this.isConLoading = false;
      }
    },
    resizePwd () {
      if (this.updateFrm.password) {
        this.rules.password_confirmation[0].required = true
      } else {
        this.rules.password_confirmation[0].required = false
        this.$refs.updateFrm.validateField('password_confirmation');
      }
    },
    submitForm () {
      let _this = this;
      this.$refs['updateFrm'].validate(async (valid) => {
        if (valid) {
          if (!_this.isAuth) {
            _this.$alert('본인인증을 진행해 주세요.', '알림', {
              confirmButtonText: '확인'
            });
            return false;
          }
          let _frm = JSON.parse(JSON.stringify(_this.updateFrm))
          let _updateFrm = removeNull(_frm);
          _this.loading = true;
          let res = await personalUpdate(_updateFrm);
          if (res.code == 200) {
            Local.remove('safeTime')
            _this.loading = false;
            if (_this.updateFrm.password) {
              await _this.$store.dispatch('logout')
              _this.$alert('새로운 비밀번호로 수정되었습니다.', '알림', {
                confirmButtonText: '확인',
                callback: action => {
                  _this.$router.replace('/login')
                }
              })
            } else {
              _this.$alert('수정되었습니다.', '알림', {
                confirmButtonText: '확인',
                callback: action => {
                  _this.$router.replace('/my')
                }
              })
            }
          } else if (res.code == -300) {
            Local.remove('safeTime')
            _this.$router.replace('/my/check')
          } else {
            _this.loading = false;
            _this.$alert(res.message, '알림', {
              confirmButtonText: '확인'
            });
          }
        } else {
          this.$alert('작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.', '알림', {
            confirmButtonText: '확인'
          })
          return false;
        }
      });
    },
    handleCheckAllChange (val) {
      let _arry = []
      this.serviceArry.forEach(item => {
        _arry.push(item.id)
      });
      this.checkedAgrValue = _arry;
      if (val) {
        this.checkAll = true;
        this.updateFrm.AD_notice = this.updateFrm.offer_notice = this.updateFrm.third_party_services = 1;
      } else {
        this.checkAll = false;
        this.updateFrm.AD_notice = this.updateFrm.offer_notice = this.updateFrm.third_party_services = 0;
      }
    },
    handleCheckedAgrChange () {
      let checkedCount = this.checkedAgrValue.length;
      if (checkedCount === this.serviceArry.length && this.updateFrm.AD_notice == 1 && this.updateFrm.offer_notice == 1 && this.updateFrm.third_party_services == 1) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
    },
    searchAds () {
      this.dialogVisible = true;  
      let _this = this;
      try {
        setTimeout(()=>{
          let _box = this.$refs.daumBox;
          this.searchAdsLoading = true;
          new daum.Postcode({
            width : '100%',
            onComplete: function (data) {
              _this.updateFrm.zip_code = data.zonecode;
              _this.updateFrm.city_area = data.address;
              _this.$refs.address.focus();
            },
            onclose: function () {
              _this.searchAdsLoading = false;
              _this.dialogVisible = false;
            },
          }).embed(_box)
        },100)
      } catch (error) {
        _this.searchAdsLoading = false;
        _this.dialogVisible = false; 
      }
    },
    closeBox(){
      this.searchAdsLoading = false;
      this.dialogVisible = false; 
    },
    setAuth () {
      let _this = this;
      try {
        this.authLoading = true;
        IMP.certification({
          merchant_uid: 'workwiz_' + new Date().getTime()
        }, function (rsp) {
          if (rsp.success) {
            _this.certification(rsp);
          } else {
            _this.authLoading = false;
            _this.$alert(rsp.error_msg, '알림', {
              confirmButtonText: '확인'
            });
          }
        });
      } catch (error) {
        _this.authLoading = false;
      }
    },
    async certification (rsp) {
      let res = await certification({ imp_uid: rsp.imp_uid });
      if (res.code == 200 && res.data && res.data.phone) {
        if (res.data.gender == 'male') {
          this.updateFrm.sex = 1
        } else {
          this.updateFrm.sex = 2
        }
        this.updateFrm.phone = res.data.phone;
        this.updateFrm.name = res.data.name;
        this.updateFrm.birthday = res.data.birthday;
        this.isAuth = true;
        this.success.auth = '인증완료';
        this.authLoading = false;
        this.isFirst = false;
      } else {
        this.isAuth = false;
        this.success.auth = '';
        this.authLoading = false;
      }
    },
    cancelAccount () {
      this.$confirm('탈퇴하기를 선택하시면, 다시 접속이 불가합니다. 정말 탈퇴하시겠습니까?', '알림', {
        confirmButtonText: '탈퇴',
        cancelButtonText: '취소',
      }).then(() => {
        this.destroy();
      });
    },
    async destroy () {
      let _this = this;
      let res = await destroy();
      if (res.code == 200) {
        await _this.$store.dispatch('logout');
        _this.$alert('성공적으로 회원 탈퇴하였습니다.', '알림', {
          confirmButtonText: '확인',
          callback: action => {
            _this.$router.replace('/')
          }
        })
      } else {
        _this.$alert('회원 탈퇴하기 실패하였습니다.', '알림', {
          confirmButtonText: '확인',
        })
      }
    }
  },
  watch: {
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/styles/myInfo.scss';
</style>